<script setup>
import { ref, watch } from 'vue'
import { getPexelsList } from '@/api/pexel'
import store from '@/store'
import Item from '../Item/Item.vue'
import { Waterfall } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'
import gsap from 'gsap'
import Pin from './Pin.vue'
const list = ref([])
const getPexelsListData = async () => {
  page.value++
  const res = await getPexelsList({
    page: page.value,
    categoryId: store.state.category.currentCategoryId
  })
  list.value.push(...res.list)
}
watch(
  () => store.state.category.currentCategoryId,
  async (newVal) => {
    const res = await getPexelsList({
      categoryId: newVal
    })

    list.value = res.list
  }
)
//分页逻辑
const page = ref(0)
const categoryId = ref('all')

const onToPins = (item) => {
  // console.log(item)
  currentPin.value = item
  history.pushState(null, null, `/pins/${item.id}`)
  isVisiblePins.value = true
}
//详情页逻辑
const isVisiblePins = ref(false)
const currentPin = ref()
const beforeEnter = (el) => {
  gsap.set(el, {
    scaleX: 0,
    scaleY: 0,
    transformOrigin: '0 0',
    translateX: currentPin.value.localtion?.translateX,
    translateY: currentPin.value.localtion?.translateY,
    opacity: 0
  })
}
const enter = (el, done) => {
  gsap.to(el, {
    duration: 0.3,
    scaleX: 1,
    scaleY: 1,
    opacity: 1,
    translateX: 0,
    translateY: 0,
    onComplete: done
  })
}
const leave = (el, done) => {
  gsap.to(el, {
    duration: 0.3,
    scaleX: 0,
    scaleY: 0,
    x: currentPin.value.localtion?.translateX,
    y: currentPin.value.localtion?.translateY,
    opacity: 0
  })
}
// 触底加载
const onLoad = () => {
  console.log('触底加载')
  getPexelsListData()
}
const isFinish = ref(false)
</script>
<template>
  <div class="w-4/5 mx-auto">
    <Infinite @load="onLoad" :isFinish>
      <Waterfall lazyload :list="list" :gutter="30">
        <template #default="{ item, url, index }">
          <Item :item="item" :key="item.id" @goDetails="onToPins" />
        </template>
      </Waterfall>
    </Infinite>
  </div>

  <transition
    :css="false"
    @before-enter="beforeEnter"
    @enter="enter"
    @leave="leave"
  >
    <Pin
      :id="currentPin.id"
      v-if="isVisiblePins"
      @close="isVisiblePins = false"
    />
  </transition>
</template>
